<template>
  <div>
    <basic-container>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>任务管理</el-breadcrumb-item>
        <el-breadcrumb-item>抽奖概率配置</el-breadcrumb-item>
      </el-breadcrumb>
    </basic-container>
    <basic-container>
      <avue-crud
        class="exclusive"
        :table-loading="loading"
        ref="crud"
        :data="data"
        v-model="form"
        :option="option"
        :page.sync="page"
        @on-load="getList"
        @refresh-change="refreshChange"
        @search-reset="form = {}"
        @search-change="searchChange"
        :span-method="objectSpanMethod"
      >
      <template slot="last" slot-scope="scope">
        {{ scope.row.edit_time }}
        <el-tag>{{ scope.row.edit_account_name }}</el-tag>
      </template>
      
      <!-- 操作 -->
      <template  slot-scope="scope" slot="menu"  >
          <el-button
            type="text"
            icon="el-icon-s-order"
            size="small"
            style="width : 200px"
            plain
            @click.stop="getMultilingualDetail(scope.row)"
            >编辑</el-button>
      </template>
      
      <el-table-column
        prop="last"
        label="最后操作信息">
      </el-table-column>
      </avue-crud>
    </basic-container>
    <!-- 弹出框 -->
    <el-dialog
      title="编辑"
      :visible.sync="multilingualDialogVisible"
      :append-to-body="true"
    >
      <el-form :model="data" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="保底奖品：">
              <el-select  v-model="this.templateValue"  placeholder="请选择保底奖品"  @change="selectedChange">
                  <el-option
                    v-for="item in data"
                    :key="item.id"
                    :label="item.prize_name"
                    :value="item.id"/>
                
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8"></el-col>
          <el-col :span="8">
            总概率: {{this.probabilitySum}}%
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="1" ></el-col>
          <el-col :span="7" ><strong>奖品名称</strong></el-col>
          <el-col :span="1" ></el-col>
          <el-col :span="7"><strong>发放数量(小时)</strong></el-col>
          <el-col :span="8"><strong>概率%</strong></el-col>
        </el-row><br/>
        <div v-for="(keyItem,index) in Object.keys(data)" :key="index">
          <el-row>
            <el-col :span="1" ></el-col>
            <el-col :span="7" >{{data[keyItem].prize_name}}</el-col>
            <el-col :span="1" ></el-col>
            <el-col :span="7">
              <el-input v-model="data[keyItem].issued_num" style="width:100px"></el-input>
            </el-col>
            <el-col :span="8">
              <el-input v-model="data[keyItem].probability" style="width:100px" @blur="calculateProbability()"></el-input>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="multilingualDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAllRow()"
          >修 改</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { common } from "@/api/cat/httpRequest";
import { catUrl } from "@/config/env";

import { userLuckDraw as baseURL, uploadFile } from "@/api/cat/baseUrls";
import favoriteBookinfo from '../../pc/featuredFirst/home/favoriteBookinfo.vue';

export default {
  components: { favoriteBookinfo },
  data() {
    return {
      item1:[],//存放合并行数据
      loading: false,
      page: {
        total: 0,
        pageSize: 10,
      },
      type: true,
      data: [],
      multilingualDialogVisible: false,
      probabilitySum: 0,
      templateValue: 0,
      params: {},
      form: {},
      option: {
        index: true,
        excelBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        border: true,
        dialogModal: true,
        tip: true,
        indexLabel: "编号",
        dialogClickModal: false,
        column: [
          {
            label: "奖品名称",
            prop: "prize_name",
            type: 'input'
          },
          {
            label: "历史发放数量",
            prop: "history_num",
            type: "input",
            editDisplay: false,
            editDisabled: false,
          },
          {
            label: "每小时发放数量",
            prop: "issued_num",
            type: 'input'
          },
          {
            label: "当前剩余数量(小时)",
            prop: "today_surplus_num",
            editDisplay: false,
            editDisabled: false,
            type: 'input'
          },
          {
            label: "概率",
            prop: "probability",
            type: 'input'
          },
          {
            label: "是否保底",
            prop: "is_last",
            type: 'input',
            row: true,
            dicData: [
              {
                label: "是",
                value: 0,
              },
              {
                label: "否",
                value: 1,
              }
            ],
          },
          {
            label: "最后操作信息",
            prop: "last",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            addDisabled: false,
            editDisabled: false,
            readonly: true,
            slot: true,
          },
        ],
      },
    };
  },
  updated: function () {
    let itemDot1 = 0;
    let item1 = [];
    this.data.forEach((item, index) => {
      if (index === 0) {//第一行
        item1.push(1)
      } else {
        //第一列
        if (item.last === this.data[index - 1].last) {// // 判断当前元素与上一个元素是否相同 data为表格数据对象  id为合并列字段
          item1[itemDot1] += 1;
          item1.push(0)
        } else {
          itemDot1 = index
          item1.push(1)
        }
      }
    })
    this.item1 = item1;
  },
  methods: {
    /**获取列表 */
    async getList() {
      //清空表格列表
      this.data = [];
      //发送请求获取数据
      let response = await common(
        baseURL.list,
        { ...this.params },
        this.page,
        "GET"
      );
      this.page = response.page;
      this.data = response.data;
      this.probabilitySum = 0;
      for (var i=0;i<this.data.length;i++){ 
          this.probabilitySum = this.probabilitySum+Number(this.data[i].probability);
      }
    },

    //合并表格
    objectSpanMethod:function ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 7) {
        const row1 = this.item1[rowIndex];
        const col1 = row1 > 0 ? 1 : 0; 
        
        return {
          rowspan: row1,
          colspan: col1,
        };
      }else if(columnIndex === 8){
        if(rowIndex === 0){
          return {
            rowspan: 1,
            colspan: 1,
          };
        }else{
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    
    /**编辑弹窗 */
    async getMultilingualDetail(row) {
      //编辑页面的弹框默认值
      for (var i=0;i<this.data.length;i++){ 
        if(this.data[i].is_last === 0){
            this.templateValue = this.data[i].id;
        }
      }
      this.multilingualDialogVisible = true;
    },

    /** 计算概率必须等于100 */
    async calculateProbability() {
      this.probabilitySum = 0;
      for (var i=0;i<this.data.length;i++){ 
          this.probabilitySum = this.probabilitySum+Number(this.data[i].probability);
      }
    },

    /** 编辑界面选择框绑定值 */
    async selectedChange(val) {
      console.log("val:"+val);
      this.templateValue = val;
      let selectedId = Number(val);
      for (var i=0;i<this.data.length;i++){ 
        if(Number(this.data[i].id) === selectedId){
            this.data[i].is_last = 0;
        }else{
            this.data[i].is_last = 1; 
        }
      }
    },

    /**编辑 */
    async updateAllRow() {
      // 深拷贝
      let params = this.data.map(o => Object.assign({}, o));
      // 处理服务器报错问题 code = 0
      for (const key in params) {
        // 删除id属性
        delete params[key].history_num;
      }
      if(this.probabilitySum === 100){
        let res = await common(baseURL.update, params, null, "PUT");
        if (res == null) {
          loading();
          return;
        }
        this.getList();
        done();
      }else{
        alert('总概率必须为100%,当前为:'+this.probabilitySum+'%');
      }
    },

    /**刷新 */
    refreshChange() {
      this.getList();
    },
    /**搜索 */
    searchChange(params, done) {
      this.params = params;
      this.page.currentPage = 1;
      this.getList();
      if (done) done();
    },
  },
};
</script>